package com.cn.xiongmeng.czlxz.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;

/* 测试成功 */
public class OaidUtils {
    public interface OaidConfirmCallback {
        void onConfirm(boolean isAgreed);
    }
    public static void oaidConfirm(Context context, OaidConfirmCallback callback){
        // 1、缓存中，存的oaidIsAgreed为true，则返回true
        SharedPreferences prefs = context.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        boolean oaidIsAgreed = prefs.getBoolean("oaidIsAgreed", false);
        if (oaidIsAgreed) {
            if (callback != null) {
                callback.onConfirm(true);
            }
            return;
        }
        new Handler(Looper.getMainLooper()).post(() -> {
            showOaidConsentDialog(context, callback);
        });
    }
    public static void showOaidConsentDialog(Context context, OaidConfirmCallback callback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("关于收集OAID");
        builder.setMessage("为了提供更好的服务和个性化体验，我们需要收集您的OAID（Open Device Identifier）。OAID是一种用于广告和分析目的的设备标识符，它可以帮助我们更好地了解用户行为，优化应用功能。我们承诺将严格遵守隐私政策，保护您的个人信息安全。请问您是否同意我们收集您的OAID？");

        builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences prefs = context.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("oaidIsAgreed", true);
                editor.apply(); // apply异步，commit同步
                if (callback != null) {
                    callback.onConfirm(true);
                }
            }
        });

        builder.setNegativeButton("不同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences prefs = context.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("oaidIsAgreed", false);
                editor.apply(); // apply异步，commit同步
                if (callback != null) {
                    callback.onConfirm(false);
                }
                dialog.dismiss();
            }
        });

        builder.setCancelable(false); // 设置对话框不可取消
        builder.show();
    }
}
